<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="showAddDialog"
      >添加</el-button
    >

    <el-table :data="trademarkList" style="width: 100%; margin: 20px 0" border>
      <el-table-column label="序号" width="80" align="center" type="index">
      </el-table-column>

      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>

      <el-table-column label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt=" " style="width: 80px; height: 60px" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="showUpdateDialog(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTrademark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!-- @size-change="handleSizeChange" @current-change="handleCurrentChange" -->
    <el-pagination
      style="text-align: center"
      @current-change="getTrademarkList"
      @size-change="handleSizeChange"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :pager-count="5"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>

    <!-- dialog嵌套form -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="tmForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <!-- 上传 -->
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Trademark",
  data() {
    var validateName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌名2到10位"));
      } else {
        callback();
      }
    };
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],
      dialogFormVisible: false,
      // imageUrl: "",
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          // {
          //   min: 3,
          //   max: 5,
          //   message: "长度在 3 到 5 个字符",
          //   trigger: "change",
          // },

          { validator: validateName, trigger: "change" },
        ],
        logoUrl: [{ required: true, message: "请上传图片" }],
      },
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    //获取分页列表
    async getTrademarkList(page = 1) {
      this.page = page;
      try {
        const result = await this.$API.trademark.getPageList(
          this.page,
          this.limit
        );
        if (result.code === 20000 || result.code === 200) {
          // alert("获取商品列表成功");
          this.trademarkList = result.data.records;
          this.total = result.data.total;
        } else {
          alert("获取商品列表失败");
        }
      } catch (error) {
        alert("请求获取商品列表失败");
      }
    },

    // handleCurrentChange(page) {
    //   this.page = page;
    //   this.getTrademarkList()
    // },

    // 修改每页显示的数量
    handleSizeChange(limit) {
      this.limit = limit;
      this.getTrademarkList();
    },

    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.tmForm.logoUrl = res.data || file.response.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //点击添加
    showAddDialog() {
      this.dialogFormVisible = true;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },
    //点击修改
    showUpdateDialog(row) {
      this.dialogFormVisible = true;
      this.tmForm = { ...row };
    },
    //点击确定按钮，添加或者修改品牌
    addOrUpdateTrademark() {
      this.$refs.tmForm.validate(async (valid) => {
        if (valid) {
          //获取请求体参数
          let trademark = this.tmForm;
          //整理参数(需要整理再整理)
          // 发请求
          try {
            const result = await this.$API.trademark.addOrUpdate(trademark);
            console.log(result);
            if (result.code === 20000 || result.code == 200) {
              //提示
              this.$message.success(
                trademark.id ? "修改品牌成功" : "添加品牌成功"
              );
              //关闭dialog
              this.dialogFormVisible = false;
              //根据是添加还是修改，返回列表页，重新获取数据的页面是不同的
              this.getTrademarkList(trademark.id ? this.page : 1);
            } else {
              //失败了干啥
              alert(trademark.id ? "修改品牌失败" : "添加品牌失败");
            }
          } catch (error) {
            alert(trademark.id ? "请求修改品牌失败" : "请求添加品牌失败");
          }
        } else {
          return false;
        }
      });
    },
    //点击删除
    deleteTrademark(row) {
      this.$confirm(`此操作将永久删除${row.tmName}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        // center: true,
      })
        .then(async () => {
          try {
            const result = await this.$API.trademark.remove(row.id);
            if (result.code === 20000 || result.code == 200) {
              this.$message.success("删除成功");
              this.getTrademarkList(
                this.trademarkList.length > 1 ? this.page : this.page - 1
              );
            }else{
             this.$message.error('删除商品失败')
            }
          } catch (error) {
            this.$message.error('请求删除商品失败')
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>